const Router = require('koa-router')
const random = require('string-random')
const nodeMailer = require('nodemailer')
const _ = require('lodash')
const uuidv1 = require('uuid')
const { VCode, ECode } = require('./utils/redis')
const settings = require('./utils').settings
const { smtp } = require('./utils/dbsconfig')
const emailHtml = require('./utils/emailHtml')
const utils = require('./utils')
const { error, INFO } = require('./utils/error')
const apiError = (info) => {
  error('50000', __filename, info)
}
const {
  requestBanner,
  requestNewsList,
  requestIPAddress,
  requestSearch
} = require('./api/public')

const router = new Router({
  prefix: '/api/public'
})

router.get('/banner', async (ctx) => {
  let result = {}
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestBanner()
    if (status === 200 && data.statu === 0) {
      code = 1
      result = data.data.map((item) => {
        return {
          id: item.id,
          name: item.title,
          imgUrl: item.img
        }
      })
    }
  } catch (error) {
    apiError('GET-banner')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})
router.get('/search', async (ctx) => {
  const { op, search, page, limit } = ctx.query
  let result = []
  let code = -1
  let msg = ''
  let len = 10
  try {
    const { status, data } = await requestSearch({
      op: Number(op) + 1,
      data: search,
      curr: page,
      limit
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      result = data.data.map((item) => {
        return {
          id: item.id,
          title: item.title,
          content: item.content,
          author: {
            id: item.authorId,
            name: item.authorName
          },
          classId: item.plateId,
          mapId: item.classId,
          time: item.date,
          browse: item.browse,
          comments: item.comments,
          imgUrl: item.img
        }
      })
      len = +data.msg
    }
  } catch (error) {
    apiError('GET-search')
    msg = INFO['50000']
    console.log(error)
  } finally {
    ctx.body = {
      code,
      data: result,
      msg,
      len
    }
  }
})

router.get('/news', async (ctx) => {
  const { limit, page, classId, mapId } = ctx.query
  let id = 0
  if (classId) {
    if (mapId !== '0') {
      id = mapId
    } else {
      id = -classId
    }
  }
  let result = {}
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestNewsList({
      limit,
      curr: page,
      id
    })

    if (status === 200 && data.statu === 0) {
      if (_.isEmpty(data.data)) {
        code = -1
        msg = '没有数据拉'
      } else {
        code = 1
        result = data.data.map((item) => {
          return {
            id: item.id,
            title: item.title,
            content: item.content,
            author: {
              id: item.authorId,
              name: item.authorName
            },
            classId: item.plateId,
            mapId: item.classId,
            time: item.date,
            browse: item.browse,
            comments: item.comments,
            imgUrl: item.img
          }
        })
      }
    }
  } catch (error) {
    apiError('GET-news')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})
router.get('/VCode', async (ctx) => {
  const code = random(4)
  const uuid = uuidv1()
  await VCode.set(uuid, code)
  ctx.body = {
    code: 1,
    data: {
      code,
      uuid
    }
  }
})
router.get('/ECode', async (ctx) => {
  let ip = utils.getClientIp(ctx.req)
  let city = '内网IP'
  const { status, data } = await requestIPAddress(ip)
  if (status === 200 && data.code === 0) {
    const body = data.data
    ip = body.ip
    city = `${body.region}省 ${body.city}市`
  }
  const { email } = ctx.query
  const saveExprire = await ECode.get(email, 'expire')
  if (saveExprire && utils.getTime() - saveExprire < 60 * 1000) {
    ctx.body = {
      code: -1,
      msg: '验证请求过于频繁，1分钟内1次'
    }
    return false
  }
  const transporter = nodeMailer.createTransport({
    host: smtp.host,
    port: 587,
    secure: false,
    auth: {
      user: smtp.user,
      pass: smtp.pass
    }
  })
  const ko = {
    code: smtp.code(),
    expire: smtp.expire(),
    email,
    from: smtp.user
  }
  const mailOptions = {
    from: `信息青年<${ko.from}>`,
    to: ko.email,
    subject: '欢迎来到信息青年',
    html: emailHtml({
      url: settings.APP_URL,
      code: ko.code,
      ip,
      city
    })
  }
  await transporter.sendMail(mailOptions, async (error) => {
    if (error) {
      return error
    } else {
      await ECode.set(ko.email, ko.code, ko.expire)
    }
  })
  ctx.body = {
    code: 0,
    msg: '验证码已发送，可能会有延迟，有效期1分钟'
  }
})

module.exports = router
